<template>
  <div class="my-tickets">
    <div class="page-header">
      <h2>我的工单</h2>
      <p>管理您提交的SQL变更工单</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card" @click="quickFilter('')">
            <div class="stats-content">
              <div class="stats-number">{{ stats.total }}</div>
              <div class="stats-label">总工单</div>
            </div>
            <el-icon class="stats-icon"><Document /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card pending" @click="quickFilter('pending')">
            <div class="stats-content">
              <div class="stats-number">{{ stats.pending }}</div>
              <div class="stats-label">待审核</div>
            </div>
            <el-icon class="stats-icon"><Clock /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card approved" @click="quickFilter('approved')">
            <div class="stats-content">
              <div class="stats-number">{{ stats.approved }}</div>
              <div class="stats-label">已批准</div>
            </div>
            <el-icon class="stats-icon"><Check /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card executed" @click="quickFilter('executed')">
            <div class="stats-content">
              <div class="stats-number">{{ stats.executed }}</div>
              <div class="stats-label">已执行</div>
            </div>
            <el-icon class="stats-icon"><CircleCheck /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filters.status" placeholder="工单状态" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="草稿" value="draft" />
            <el-option label="待审核" value="pending" />
            <el-option label="已批准" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="执行中" value="executing" />
            <el-option label="已执行" value="executed" />
            <el-option label="执行失败" value="failed" />
            <el-option label="已撤回" value="withdrawn" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.priority" placeholder="优先级" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="低" value="low" />
            <el-option label="普通" value="normal" />
            <el-option label="高" value="high" />
            <el-option label="紧急" value="urgent" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.request_type" placeholder="请求类型" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="查询" value="query" />
            <el-option label="DML变更" value="dml" />
            <el-option label="DDL变更" value="ddl" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="filters.search"
            placeholder="搜索标题或描述"
            clearable
            @input="handleSearchChange"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </div>

    <!-- 工单列表 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tickets"
        stripe
        style="width: 100%"
        @row-click="handleRowClick"
        class="tickets-table"
        :header-cell-style="{ background: '#f8f9fa', color: '#606266', fontWeight: '600' }"
        :row-class-name="getRowClassName"
      >
        <el-table-column prop="id" label="工单ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column label="申请人" width="120">
          <template #default="{ row }">
            <span v-if="row.requester">{{ row.requester.username }}</span>
            <span v-else-if="row.requester_name">{{ row.requester_name }}</span>
            <span v-else class="text-muted">未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="request_type_display" label="类型" width="100" />
        <el-table-column prop="status" label="状态" width="110">
          <template #default="{ row }">
            <el-tag
              :type="getStatusTagType(row.status)"
              size="small"
              :class="['status-tag', { 'executing': row.status === 'executing' }]"
            >
              <i v-if="row.status === 'executing'" class="el-icon-loading"></i>
              {{ row.status_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTagType(row.priority)" size="small">
              {{ row.priority_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="目标数据库" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.database_instance?.name || row.database_instance_name || '未指定' }}
          </template>
        </el-table-column>
        <el-table-column prop="reviewer" label="审核人" width="120">
          <template #default="{ row }">
            <span v-if="row.reviewer">{{ row.reviewer.username }}</span>
            <span v-else class="text-muted">未分配</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click.stop="viewDetail(row.id)"
                class="action-btn"
              >
                查看
              </el-button>
              <el-button
                v-if="row.status === 'approved'"
                type="success"
                size="small"
                @click.stop="executeTicket(row)"
                class="action-btn"
              >
                执行
              </el-button>
              <el-button
                v-if="row.status === 'pending'"
                type="warning"
                size="small"
                @click.stop="withdrawTicket(row)"
                class="action-btn"
              >
                撤回
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 工单详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="工单详情"
      width="80%"
      :before-close="handleDetailClose"
    >
      <div v-if="detailDialog.data" class="ticket-detail">
        <!-- 状态流程 -->
        <div class="status-flow">
          <el-steps :active="getStatusStep(detailDialog.data.status)" finish-status="success">
            <el-step title="草稿" description="工单创建" />
            <el-step title="待审核" description="等待审核" />
            <el-step title="已批准" description="审核通过" />
            <el-step title="执行中" description="正在执行" />
            <el-step title="已完成" description="执行完成" />
          </el-steps>
        </div>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单ID">{{ detailDialog.data.id }}</el-descriptions-item>
          <el-descriptions-item label="标题">{{ detailDialog.data.title }}</el-descriptions-item>
          <el-descriptions-item label="申请人">
            <span v-if="detailDialog.data.requester">
              {{ detailDialog.data.requester.username }}
              <span v-if="detailDialog.data.requester.full_name">
                ({{ detailDialog.data.requester.full_name }})
              </span>
            </span>
            <span v-else-if="detailDialog.data.requester_name">
              {{ detailDialog.data.requester_name }}
            </span>
            <span v-else class="text-muted">未知</span>
          </el-descriptions-item>
          <el-descriptions-item label="审核人">
            <span v-if="detailDialog.data.reviewer">
              {{ detailDialog.data.reviewer.username }}
              <span v-if="detailDialog.data.reviewer.first_name || detailDialog.data.reviewer.last_name">
                ({{ detailDialog.data.reviewer.first_name }} {{ detailDialog.data.reviewer.last_name }})
              </span>
            </span>
            <span v-else-if="detailDialog.data.reviewer_name">
              {{ detailDialog.data.reviewer_name }}
            </span>
            <span v-else class="text-muted">未分配</span>
          </el-descriptions-item>
          <el-descriptions-item label="请求类型">{{ detailDialog.data.request_type_display }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(detailDialog.data.status)">
              {{ detailDialog.data.status_display }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTagType(detailDialog.data.priority)" size="small">
              {{ detailDialog.data.priority_display }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="目标数据库">
            {{ detailDialog.data.database_instance?.name || detailDialog.data.database_instance_name || '未指定' }}
            <span v-if="detailDialog.data.database_instance?.database_type">
              ({{ detailDialog.data.database_instance.database_type }})
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(detailDialog.data.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="审核时间">
            {{ detailDialog.data.reviewed_at ? formatDateTime(detailDialog.data.reviewed_at) : '未审核' }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <h4>描述</h4>
          <p>{{ detailDialog.data.description }}</p>
        </div>

        <div class="detail-section">
          <h4>SQL内容</h4>
          <el-input
            v-model="detailDialog.data.sql_content"
            type="textarea"
            :rows="10"
            readonly
            class="sql-content"
          />
        </div>

        <div v-if="detailDialog.data.review_comment" class="detail-section">
          <h4>审核意见</h4>
          <p>{{ detailDialog.data.review_comment }}</p>
        </div>

        <div v-if="detailDialog.data.execution_result" class="detail-section">
          <h4>执行结果</h4>
          <pre class="execution-result">{{ detailDialog.data.execution_result }}</pre>
        </div>

        <!-- 操作历史 -->
        <div v-if="detailDialog.data.operation_history && detailDialog.data.operation_history.length > 0" class="detail-section">
          <h4>操作历史</h4>
          <el-timeline>
            <el-timeline-item
              v-for="history in detailDialog.data.operation_history"
              :key="history.id"
              :timestamp="formatDateTime(history.created_at)"
              placement="top"
            >
              <div class="history-item">
                <div class="history-action">
                  <el-tag :type="getActionTagType(history.action)" size="small">
                    {{ history.action_display }}
                  </el-tag>
                  <span class="history-user">{{ history.user.username }}</span>
                </div>
                <div class="history-description">{{ history.description }}</div>
                <div class="history-ip">IP: {{ history.ip_address }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDetailClose">关闭</el-button>
          <el-button
            v-if="detailDialog.data && detailDialog.data.status === 'approved'"
            type="success"
            @click="executeTicketFromDetail"
          >
            执行工单
          </el-button>
          <el-button
            v-if="detailDialog.data && detailDialog.data.can_withdraw"
            type="warning"
            @click="withdrawTicketFromDetail"
          >
            撤回工单
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 执行确认对话框 -->
    <el-dialog
      v-model="executeDialog.visible"
      title="确认执行SQL"
      width="60%"
      :before-close="handleExecuteDialogClose"
    >
      <div v-if="executeDialog.data" class="execute-confirm">
        <el-alert
          :title="executeDialog.isDangerous ? '⚠️ 危险SQL操作警告' : '确认执行SQL'"
          :type="executeDialog.isDangerous ? 'error' : 'warning'"
          :description="executeDialog.isDangerous ? `检测到危险操作：${executeDialog.dangerousKeyword}，执行后无法撤销！` : '请确认SQL内容正确后执行'"
          show-icon
          :closable="false"
          style="margin-bottom: 20px"
        />

        <el-descriptions :column="2" border style="margin-bottom: 20px">
          <el-descriptions-item label="工单ID">{{ executeDialog.data.id }}</el-descriptions-item>
          <el-descriptions-item label="标题">{{ executeDialog.data.title }}</el-descriptions-item>
          <el-descriptions-item label="目标数据库">{{ executeDialog.data.database_instance_name }}</el-descriptions-item>
          <el-descriptions-item label="SQL类型">{{ executeDialog.data.request_type_display }}</el-descriptions-item>
        </el-descriptions>

        <div class="sql-content">
          <h4>SQL内容：</h4>
          <el-input
            v-model="executeDialog.data.sql_content"
            type="textarea"
            :rows="8"
            readonly
            class="sql-textarea"
          />
        </div>

        <div v-if="executeDialog.isDangerous" class="danger-confirm" style="margin-top: 20px">
          <el-checkbox v-model="executeDialog.dangerConfirmed">
            我已确认SQL内容无误，了解此操作的风险并愿意承担后果
          </el-checkbox>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleExecuteDialogClose">取消</el-button>
          <el-button
            type="danger"
            :disabled="executeDialog.isDangerous && !executeDialog.dangerConfirmed"
            :loading="executeDialog.loading"
            @click="confirmExecute"
          >
            {{ executeDialog.isDangerous ? '确认执行危险操作' : '确认执行' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Document, Clock, Check, CircleCheck } from '@element-plus/icons-vue'
import { sqlAPI } from '@/api/sql'
import { sqlWorkOrderAPI } from '@/api/sqlWorkOrder'

// 响应式数据
const loading = ref(false)
const tickets = ref([])

// 筛选条件
const filters = reactive({
  status: '',
  priority: '',
  request_type: '',
  search: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

// 执行确认对话框
const executeDialog = reactive({
  visible: false,
  data: null,
  loading: false,
  isDangerous: false,
  dangerousKeyword: '',
  dangerConfirmed: false
})

// 搜索防抖
let searchTimeout = null

// 统计数据
const stats = computed(() => {
  const total = tickets.value.length
  const pending = tickets.value.filter(t => t.status === 'pending').length
  const approved = tickets.value.filter(t => t.status === 'approved').length
  const executed = tickets.value.filter(t => t.status === 'executed').length

  return {
    total,
    pending,
    approved,
    executed
  }
})

// 获取工单列表
const fetchTickets = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...filters
    }
    
    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    // 使用新的工单API，只获取当前用户的工单
    const response = await sqlWorkOrderAPI.getMyWorkOrders(params)
    tickets.value = response.results || response.data?.results || []
    pagination.total = response.count || response.data?.count || 0
  } catch (error) {
    console.error('获取工单列表失败:', error)
    ElMessage.error('获取工单列表失败')
  } finally {
    loading.value = false
  }
}

// 筛选变化处理
const handleFilterChange = () => {
  pagination.page = 1
  fetchTickets()
}

// 快速筛选
const quickFilter = (status) => {
  filters.status = status
  pagination.page = 1
  fetchTickets()
}

// 搜索变化处理（防抖）
const handleSearchChange = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    pagination.page = 1
    fetchTickets()
  }, 500)
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchTickets()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchTickets()
}

// 行点击处理
const handleRowClick = (row) => {
  viewDetail(row.id)
}

// 查看详情
const viewDetail = async (id) => {
  try {
    const response = await sqlWorkOrderAPI.getWorkOrder(id)
    detailDialog.data = response
    detailDialog.visible = true
  } catch (error) {
    console.error('获取工单详情失败:', error)
    ElMessage.error('获取工单详情失败')
  }
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailDialog.visible = false
  detailDialog.data = null
}

// 撤回工单
const withdrawTicket = async (ticket) => {
  try {
    await ElMessageBox.confirm(
      `确定要撤回工单"${ticket.title}"吗？撤回后将无法恢复。`,
      '确认撤回',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await sqlWorkOrderAPI.withdrawWorkOrder(ticket.id)
    ElMessage.success('工单撤回成功')
    fetchTickets()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回工单失败:', error)
      ElMessage.error('撤回工单失败')
    }
  }
}

// 从详情页撤回工单
const withdrawTicketFromDetail = async () => {
  await withdrawTicket(detailDialog.data)
  handleDetailClose()
}

// 执行工单
const executeTicket = async (ticket) => {
  executeDialog.data = ticket
  executeDialog.visible = true
  executeDialog.isDangerous = false
  executeDialog.dangerousKeyword = ''
  executeDialog.dangerConfirmed = false
  executeDialog.loading = false
}

// 从详情页执行工单
const executeTicketFromDetail = async () => {
  executeTicket(detailDialog.data)
}

// 关闭执行确认对话框
const handleExecuteDialogClose = () => {
  executeDialog.visible = false
  executeDialog.data = null
  executeDialog.isDangerous = false
  executeDialog.dangerousKeyword = ''
  executeDialog.dangerConfirmed = false
  executeDialog.loading = false
}

// 确认执行
const confirmExecute = async () => {
  if (!executeDialog.data) return

  executeDialog.loading = true
  try {
    const requestData = {}
    if (executeDialog.isDangerous) {
      requestData.confirm_dangerous = true
    }

    await sqlWorkOrderAPI.executeWorkOrder(executeDialog.data.id, requestData)

    ElMessage.success('工单执行成功')
    handleExecuteDialogClose()

    // 刷新列表
    await fetchTickets()

    // 如果详情对话框打开，也刷新详情
    if (detailDialog.visible && detailDialog.data?.id === executeDialog.data.id) {
      const response = await sqlWorkOrderAPI.getWorkOrder(executeDialog.data.id)
      detailDialog.data = response
    }

  } catch (error) {
    console.error('执行工单失败:', error)

    // 检查是否是危险SQL需要确认
    if (error.response?.data?.error === 'dangerous_sql') {
      executeDialog.isDangerous = true
      executeDialog.dangerousKeyword = error.response.data.dangerous_keyword
      ElMessage.warning(`检测到危险SQL操作：${error.response.data.dangerous_keyword}，请确认后重新执行`)
    } else {
      ElMessage.error(error.response?.data?.error || '执行工单失败')
      handleExecuteDialogClose()
    }
  } finally {
    executeDialog.loading = false
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    executing: 'primary',
    executed: 'success',
    failed: 'danger',
    withdrawn: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取优先级标签类型
const getPriorityTagType = (priority) => {
  const priorityMap = {
    low: 'info',
    normal: 'primary',
    high: 'warning',
    urgent: 'danger'
  }
  return priorityMap[priority] || 'primary'
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取状态对应的步骤
const getStatusStep = (status) => {
  const statusSteps = {
    draft: 0,
    pending: 1,
    approved: 2,
    executing: 3,
    executed: 4,
    rejected: 1, // 被拒绝停留在审核步骤
    failed: 3,   // 执行失败停留在执行步骤
    withdrawn: 1 // 撤回停留在审核步骤
  }
  return statusSteps[status] || 0
}

// 获取操作类型标签样式
const getActionTagType = (action) => {
  const actionMap = {
    create_request: 'primary',
    review_request: 'warning',
    execute_request: 'success',
    withdraw_request: 'info',
    query_execute: ''
  }
  return actionMap[action] || ''
}

// 获取表格行的CSS类名
const getRowClassName = ({ row }) => {
  return `status-${row.status}`
}

// 组件挂载时获取数据
onMounted(() => {
  fetchTickets()
})
</script>

<style scoped>
.my-tickets {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-card {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border: 1px solid #e4e7ed;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.stats-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #409eff, #67c23a, #e6a23c, #f56c6c);
}

.stats-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stats-content {
  position: relative;
  z-index: 2;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.stats-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 40px;
  color: rgba(64, 158, 255, 0.2);
  z-index: 1;
}

.stats-card.pending .stats-icon {
  color: rgba(230, 162, 60, 0.2);
}

.stats-card.approved .stats-icon {
  color: rgba(103, 194, 58, 0.2);
}

.stats-card.executed .stats-icon {
  color: rgba(64, 158, 255, 0.2);
}

.filter-section {
  margin-bottom: 20px;
  padding: 24px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.table-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 20px;
  text-align: right;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
  background-color: #fafafa;
  border-radius: 0 0 8px 8px;
}

.text-muted {
  color: #909399;
}

.ticket-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.status-flow {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.detail-section {
  margin: 20px 0;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
}

.sql-content {
  font-family: 'Courier New', monospace;
}

.execution-result {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  white-space: pre-wrap;
  max-height: 300px;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.history-item {
  padding: 10px 0;
}

.history-action {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
}

.history-user {
  font-weight: 500;
  color: #303133;
}

.history-description {
  color: #606266;
  margin-bottom: 3px;
}

.history-ip {
  font-size: 12px;
  color: #909399;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}

.action-btn {
  min-width: 60px;
  margin: 0 !important;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 状态标签样式 */
.status-tag {
  font-weight: 500;
  border-radius: 4px;
}

.status-tag.executing {
  animation: pulse 1.5s ease-in-out infinite;
}

.status-tag.executing .el-icon-loading {
  margin-right: 4px;
  animation: rotate 1s linear infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 执行确认对话框样式 */
.execute-confirm {
  padding: 10px 0;
}

.execute-confirm .sql-content h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-weight: 600;
}

.sql-textarea :deep(.el-textarea__inner) {
  font-family: 'Courier New', 'Monaco', 'Menlo', monospace;
  font-size: 13px;
  line-height: 1.4;
  background-color: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.danger-confirm {
  padding: 15px;
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 6px;
  margin-top: 20px;
}

.danger-confirm .el-checkbox {
  color: #e6a23c;
  font-weight: 500;
}

/* 表格样式优化 */
.tickets-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tickets-table :deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

.tickets-table :deep(.el-table__body tr:hover > td) {
  background-color: #f0f9ff !important;
}

.tickets-table :deep(.el-table td) {
  padding: 12px 0;
}

.tickets-table :deep(.el-table th) {
  padding: 16px 0;
  border-bottom: 2px solid #e4e7ed;
}

/* 不同状态工单的行样式 */
.tickets-table :deep(.el-table__body .status-approved) {
  background-color: #f0f9ff;
}

.tickets-table :deep(.el-table__body .status-executing) {
  background-color: #fffbf0;
}

.tickets-table :deep(.el-table__body .status-executed) {
  background-color: #f0f9f0;
}

.tickets-table :deep(.el-table__body .status-failed) {
  background-color: #fef0f0;
}

/* 确保按钮在小屏幕上也能正常显示 */
@media (max-width: 1200px) {
  .action-buttons {
    flex-direction: column;
    gap: 4px;
    align-items: stretch;
  }

  .action-btn {
    width: 100%;
    min-width: auto;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-section .el-col {
    margin-bottom: 10px;
  }
  
  .table-section {
    padding: 10px;
  }
  
  .my-tickets {
    padding: 10px;
  }
}
</style>
